<?php
/**
 * Created by PhpStorm.
 * User: chl
 * Date: 2017/3/22 0022
 * Time: 17:50
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Request;
use think\Db;
Vendor('PHPExcel.Classes.PHPExcel');
class User extends Base{
    public function userList(){
        $userModel = new Bases('user');
        $get = input('param.');
        $search = search($get,'a.create_time','a.username,a.nickname');
        $where  = $search['condition'];
        if(!empty($get['type'])){
                $where .= " and a.type =".$get['type'];
                $search['display']['type'] = $get['type'];
        }
        if(!empty($get['status'])){
            $where .= " and a.status =".$get['status'];
            $search['display']['status'] = $get['status'];
        }
        if(!empty($get['is_remind'])){
            $where .= " and  a.is_remind = ".$get['is_remind'];
            $search['display']['is_remind'] = $get['is_remind'];
        }
        if(!empty($get['account_binding'])){
            if($get['account_binding']==1){
                $where .= " and  coalesce(a.username,'') <> '' and  coalesce(a.openid,'') <> '' ";
            }else if($get['account_binding']==2){
                $where .= " and  coalesce(a.openid,'') <> '' and coalesce(a.username,'') = '' ";
            }else if($get['account_binding']==3){
                $where .= " and  coalesce(a.username,'') <> '' and coalesce(a.openid,'') = ''  ";
            }
            $search['display']['account_binding'] = $get['account_binding'];
        }
        $field  = "a.*,b.expiration_time,c.name,duration";
        $join   = [['order b','a.order_id = b.order_id','LEFT'],['product c','b.product_id = c.product_id','LEFT']];
        $result['list']= Db::name('user')->alias('a')->join($join)->where($where)->field($field)->order('a.uid desc')->paginate(15,false,[
            'query' => $get,
        ]);
        return view('userList',['result'=>$result,'display'=>$search['display'],'exportwhere'=>$where]);
    }
    public function userAdd(){
        $productModel = new Bases('product');
        $userModel    = new Bases('user');
        $orderModel   = new Bases('order');
        try{

            if(Request()->isPost()){
                $post = input('param.');
                $post['integral'] =50;
                $post['create_time'] =time();
                $post['source'] = 3;
                    $validateResult = self::isMobile($post['username']);
                    if($validateResult === false){
                         throw new \LogicException('手机号码不合法',10001);
                    }
                $productId = empty($post['product_id']) ? '':$post['product_id'];
                if($productId==""){
                    $validate = $this->validate($post,'User.userAdd');
                }else{
                    $validate = $this->validate($post,'User.userProduct');
                }
                if($validate !== true){
                    throw new \LogicException($validate,1000);
                }
                unset($post['product_id']);
                $password = trim($post['password']);
                $post['password'] = password_hash($password,true);
                $rs = $userModel->insertData($post);
                if($rs !== false){
                    if(!($productId=="")){
                        $order['product_id'] =$productId;
                        $price = $productModel->find('product_id ='.$productId,'discounted_price,duration');
                        $order['money'] = $price['discounted_price'];
                        $order['order_no'] = date('Ymdhis').rand(100000,999999);
                        $order['uid'] = $rs;
                        $order['type'] = $userModel::ORDER_TYPE_DOWN;
                        $order['status'] = 2;
                        $order['create_time'] = time();
                        $order['effective_time'] = time();
                        $order['pay_time'] = time();
                        $order['expiration_time'] = strtotime(date('Y-m-d'.'00:00:00',time()))+3600*24*2-1+$price['duration'];
                        $ors = $orderModel->insertData($order);
                        if($ors !== false){
                            $userModel->updateData(['order_id'=>$ors],'uid = '.$rs);//跟新訂單
                            return self::formatSuccessResult();
                        }else{
                            return self::formatResult(406,'操作失败');
                        }
                    }
                    return self::formatSuccessResult();
                }return self::formatResult(406,'操作失败');
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $productInfo  = $productModel->selectData();
        return view('userAdd',['result'=>$productInfo]);
    }
    public function userSave(){
        $userModel= new Bases('user');
        $productModel = new Bases('product');
        try{
            $userId = intval(input('uid'));
            if(Request()->isPost()){
                $post = input('param.');
                $rs = $userModel->updateData($post);
                if($rs !== false){
                    return self::formatSuccessResult();
                }return self::formatResult(406,'操作失败');
            }
            $userOne=$userModel->find('uid ='.$userId,'uid,username,nickname,real_name,integral,type');
            $productInfo = $productModel->selectData();
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return view('userSave',['result'=>$userOne,'productInfo'=>$productInfo]);
    }

    /**改变用户状态
     * @return array
     */
    public function userStatusChange(){
        $status = input('status');
        $id = input('id');
        $status = $status==1 ? 2:1;
        $userModel = new Bases('user');
        $rs = $userModel->updateData(['status'=>$status],'uid = '.$id);
        if($rs !== false){
            return self::formatSuccessResult(['status'=>$status]);
        }return self::formatResult(406,'操作失败');

    }

    /**重置密码
     * @return array
     */
    public function userChangePwd(){
        $pwd = password_hash('123456',true);
        $id = input('id');
        $userModel = new Bases('user');
        $rs = $userModel->updateData(['password'=>$pwd],'uid = '.$id);
        if($rs !== false){
            return self::formatSuccessResult();
        }return self::formatResult(406,'操作失败');

    }
    public function export(){
        $where = substr(input('param.exportwhere'),1);
        if($where == false){
            $exprotwhere ='';
        }else{
            $exprotwhere = html_entity_decode(input('exportwhere'));
        }
        $userModel = new Bases('user');
        $field  = "a.*,b.expiration_time,c.name,duration";
        $join   = [['order b','a.order_id = b.order_id','LEFT'],['product c','b.product_id = c.product_id','LEFT']];
        $result = $userModel->joinData('a',$join,$exprotwhere,$field,'a.uid desc');
        if(empty($result)){
            $this->error('没有任何数据');
        }
        foreach($result as $k=>$v){
            $exprotInfo[$k]['ID'] = $v['uid'];
            $exprotInfo[$k]['username'] = $v['username'];
            if(!empty($v['openid']) && empty($v['username'])){
                $account_binding = '仅微信';            }else if(!empty($v['username']) && empty($v['openid'])){
                $account_binding = '仅手机';            }else if(!empty($v['openid']) && !empty($v['username'])){
                $account_binding = '手机+微信';}
            $exprotInfo[$k]['openid'] = $account_binding;
            $exprotInfo[$k]['nickname'] = $v['nickname'];
            $exprotInfo[$k]['real_name'] = $v['real_name'];
            $exprotInfo[$k]['type'] =  $v['type']==3 ? '会员':'助理';
            $exprotInfo[$k]['name'] = empty($v['name'])? '--':$v['name'];
            $exprotInfo[$k]['expiration_time'] = empty($v['expiration_time']) ? '--':date('Y-m-d ',$v['expiration_time']);
            $exprotInfo[$k]['integral'] = $v['integral'];
            $exprotInfo[$k]['source'] = $v['source']==1 ? 'PC':($v['source']==2 ? '微信':'后台添加');
            $exprotInfo[$k]['tixin'] = $v['is_remind']==1 ? '是':'否';
            $exprotInfo[$k]['last_login_time'] = empty($v['last_login_time']) ? '0':date('Y-m-d H:i:s',$v['last_login_time']);
            $exprotInfo[$k]['create_time'] = empty($v['create_time']) ? '0':date('Y-m-d H:i:s',$v['create_time']);
            $exprotInfo[$k]['status'] = $v['status'] == 1 ? '已启用' : '已禁用';
        }
        ob_clean();
        push($exprotInfo);
    }
}